package org.zeroes.Components;
import android.util.Log;
import org.zeroes.Events.*;
import com.zeroes.cons.*;
public class ZSBAnimation extends ZSSpriteBehavior{

	private float dest;

	private String pre;
	private ZSBatchLayer animLayer;
	private float start;
	public boolean backToInitialFrame=false;
	private boolean ended=false;

	
	private int dur;
	private int repeats;

	


	private int inc=1;
	private ZSSprite _subj;
	
	public ZSBAnimation(String name,ZSSprite subject,  int repeats){
		super(name,subject);

		
		this.AddIntegerProperty("*.property.repeats", repeats);
		
		this.repeats=repeats;
	
	
		this._subj=subject;
		
		this.on(subject.tag+".Animation.playing", new Callback(){
			
			public void run(String p, ZSEvent e){
				if(e.loopindex>=0)
				{
					//Log.v("gtrans"," > "+e.loopindex);
					_subj.changeRect(animLayer.rectById(pre+"-"+e.loopindex));
					
				}
					else
				{
						
						if(backToInitialFrame) _subj.changeRect(animLayer.rectById(pre+"-"+0));
					
					String[] items = e.name.split("\\.");
					ZSGameManager.AskMe().events._(items[0]+"."+items[1]+".finished", e);
					
				}
			}
		});
		
		
		this.AddAction("*.action.run", new ZSLogicUnit(){
			
			public void is(ZSComponent c, ZSLUParameters p){
				ZSBAnimation b =(ZSBAnimation)c;
				
			//	ZSSprite target = b.getSpriteProperty("Subject");
				int fc=0;
				ZSEventSheet E = ZSGameManager.AskMe().events;
				E._(_subj.tag+".Animation.start", null);
				
				int rep= b.getIntegerProperty("repeats");
				ZSSingle<Integer> sd=(ZSSingle<Integer>)p.getParamAtIndex(0);
				//String firstidx =_subj.rect.id.substring(_subj.rect.id.length()-1, _subj.rect.id.length());
				
				//pre = _subj.rect.id.substring(0,_subj.rect.id.length()-1);
				String[] items = _subj.rect.id.split("-");
				if(items.length>0){
				animLayer = (ZSBatchLayer)_subj.Layer();
				pre=items[0];
				fc=animLayer.rectCountForPrefix(pre);
				//Log.v("gtrans"," > "+firstidx+" frame count  "+fc);
				//ZSSingle<Integer> _dest=(ZSSingle<Integer>)p.getParamAtIndex(1);
				//ZSSingle<Integer> _y=(ZSSingle<Integer>)p.getParamAtIndex(2);
				/*String dir=">";
				if(p.getParamsCount()==1)
					dir=">";
				else
				{
					ZSSingle<String> _dir=(ZSSingle<String>)p.getParamAtIndex(1);
					dir=_dir.getFirst();
				}
				if(dir.equals(">")){
				dest=1.0f;
				

				start=target.opacity;

				}
				else
				{
					start=target.opacity;
		

					dest=0;
					
					
				}
				diff=dest-start;*/
			
				dur=sd.getFirst();
				if(fc>0){
				mainCondition=E.makeCustomInterval(sd.getFirst(),fc-1,rep,_subj.tag+".Animation.playing",new Condback(){
					
					public void is(String n, int idx){
						ZSEvent ev = new ZSEvent(n,null,idx);	
						
						ZSGameManager.AskMe().events._(n, ev);
						
					}
				});
				
				}
				}	
			}
		});
		
	}
}
